<script lang="ts" setup>
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { warnBox } from '@/utils/utils'
import EditDialog from './components/EditDialog.vue'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { formatDate } from '@/utils/day'
import { changeRoleStatus, delRole, listRole, roleExport } from '@/api/system/role'
import { downloadBlobFile } from '@/utils'
import type { Role, RoleQueryParams } from '@/api/system/role/type'
import ScopeDialog from './components/ScopeDialog.vue'
import { debounce } from 'es-toolkit'
import { getDicts } from '@/api/system/dict'

const sysNormalDisable = ref<IGetDictsRes>([])
const router = useRouter()
// form
const formValue = ref<RoleQueryParams & { daterange?: string[] }>({
	roleName: '',
	roleKey: '',
	status: '',
	daterange: []
})
const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '角色名称',
		prop: 'roleName'
	},

	{
		type: 'input',
		label: '权限字符',
		prop: 'roleKey'
	},

	{
		type: 'select',
		label: '状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any[],
		attrs: {
			style: 'width: 200px'
		}
	},

	{
		type: 'date-picker',
		label: '创建时间',
		prop: 'daterange',
		attrs: {
			type: 'daterange',
			startPlaceholder: '开始时间',
			endPlaceholder: '结束时间',
			valueFormat: 'YYYY-MM-DD'
		}
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<Role[]>([])
const columns = ref<TableColums[]>([
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '角色编号',
		prop: 'id'
	},
	{
		label: '角色名称',
		prop: 'roleName'
	},
	{
		label: '权限字符',
		prop: 'roleKey'
	},
	{
		label: '显示顺序',
		prop: 'roleSort'
	},
	{
		label: '状态',
		prop: 'status',
		type: 'slot'
	},
	{
		label: '创建时间',
		prop: 'createTime',
		formatter: row => formatDate(row.createTime)
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: '260px',
		align: 'center'
	}
])
// dialog
const editDialogRef = useTemplateRef('editDialogRef')

const dataScopeDialogRef = useTemplateRef('dataScopeDialogRef')

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value,
			'params[beginTime]': formValue.value.daterange?.[0],
			'params[endTime]': formValue.value.daterange?.[1]
		}
		delete params.daterange

		const res = await listRole(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

const handelAdd = () => {
	editDialogRef.value?.init('add')
}

const handelEdit = (row: Role) => {
	editDialogRef.value?.init('edit', row.id)
}
const handelDelete = async (rowId: number) => {
	await warnBox({
		title: '提示',
		message: `是否确认删除角色编号为"${rowId}"的数据项？`
	})
	await delRole(rowId)
	ElMessage.success('删除成功')
	getTableData()
}

const handleDataScope = (row: Role) => {
	dataScopeDialogRef.value?.init(row.id)
}

// 分配用户
const handleAuthRole = (row: Role) => {
	router.push('/system/role-auth/user/' + row.id)
}
function handleStatusChange(row: Role) {
	const preStatus = row.status === 0 ? 1 : 0
	const flagMsg = row.status === 0 ? '启用' : '停用'

	ElMessageBox({
		title: '提示',
		type: 'warning',
		message: `确认要"${flagMsg}""${row.roleName}"用户吗?`,
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	})
		.then(async () => {
			await changeRoleStatus(row.id, row.status)
			ElMessage.success(flagMsg + '成功')
			getTableData()
		})
		.catch(() => {
			row.status = preStatus
		})
}
const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

// 导出
const exportFn = () => {
	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value,
		'params[beginTime]': formValue.value.daterange?.[0],
		'params[endTime]': formValue.value.daterange?.[1]
	}
	delete params.daterange
	roleExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `role_${new Date().getTime()}.xlsx`)
	})
}
function init() {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>
<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						type="primary"
						@click="handelAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:role:import'])"
						@click="handleExport"
					>
						导出
					</el-button>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:role:edit']) && row.id !== 1"
						type="primary"
						link
						@click="handelEdit(row)"
					>
						修改
					</el-button>

					<el-button
						v-if="checkPermission(['system:role:edit']) && row.id !== 1"
						type="primary"
						link
						@click="handleDataScope(row)"
					>
						数据权限
					</el-button>
					<el-button
						v-if="checkPermission(['system:role:edit']) && row.id !== 1"
						type="primary"
						link
						@click="handleAuthRole(row)"
					>
						分配用户
					</el-button>
					<el-button
						v-if="checkPermission(['system:role:remove']) && row.id !== 1"
						type="danger"
						link
						@click="handelDelete(row.id)"
					>
						删除
					</el-button>
				</template>
				<template #status="{ row }">
					<el-switch
						v-model="row.status"
						:active-value="0"
						:inactive-value="1"
						@click="handleStatusChange(row)"
					/>
				</template>
			</QTable>
		</div>
		<EditDialog
			ref="editDialogRef"
			:sys-normal-disable="sysNormalDisable"
			@refresh="getTableData"
		/>
		<ScopeDialog ref="dataScopeDialogRef" />
	</div>
</template>
